package com.gf.exam.dao.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.gf.base.dao.impl.BaseDaoImpl;
import com.gf.base.type.Activity;
import com.gf.base.type.ExamType;
import com.gf.base.type.PlayMode;
import com.gf.common.bean.Page;
import com.gf.exam.dao.ExamDao;
import com.gf.exam.mapper.CellMapper;
import com.gf.exam.mapper.ExamMapper;
import com.gf.exam.model.Cell;
import com.gf.exam.model.Exam;
import com.gf.exam.model.Timer;

@Service("examDao")
public class ExamDaoImpl extends BaseDaoImpl implements ExamDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Value("${lucene.page.pageSize}")
	private int lucenePageSize;

	/**
	 * select * from exam order by updatetime desc limit 1
	 */
	@Value("${examDao.queryLatestExamSql}")
	private String queryLatestExamSql;
	@Value("${examDao.queryExamNumberSqlByUserId}")
	private String queryExamNumberSqlByUserId;

	/**
	 * select * from exam where updatetime>?
	 */
	@Value("${examDao.queryExamByUpdatetimeSql}")
	private String queryExamByUpdatetimeSql;

	/**
	 * select * from exam
	 */
	@Value("${examDao.queryAllExamForLuceneSql}")
	private String queryAllExamForLuceneSql;

	/**
	 * select count(1) from exam
	 */
	@Value("${examDao.queryExamNumberSql}")
	private String queryExamNumberSql;

	/**
	 * insert into exam
	 * (userId,userName,title,introduction,cellNo,active,repeatFrom
	 * ,repeatTo,playMode
	 * ,repeatTime,createtime,updatetime,timerH,timerM,timerS,examType)
	 * values(?,?,?,?,?,?,?,?,?,?,current_timestamp,current_timestamp,?,?,?,?)
	 */
	@Value("${examDao.insertSql}")
	private String insertSql;

	/**
	 * update exam set
	 * title=?,introduction=?,cellNo=?,active=?,repeatFrom=?,repeatTo
	 * =?,playMode=
	 * ?,repeatTime=?,updatetime=current_timestamp,timerH=?,timerM=?,
	 * timerS=?,examType=? where id=?
	 */
	@Value("${examDao.updateSql}")
	private String updateSql;

	/**
	 * update exam set examType=? where id=?
	 */
	@Value("${examDao.updateExamTypeSql}")
	private String updateExamTypeSql;

	/**
	 * select * from exam where id=?
	 */
	@Value("${examDao.queryByIdSql}")
	private String queryByIdSql;
	
	/**
	 * select * from exam where id=? and userId=?
	 */
	@Value("${examDao.queryByIdAndUserIdSql}")
	private String queryByIdAndUserIdSql;

	/**
	 * select * from exam where id in (?)
	 */
	@Value("${examDao.queryBatchByIdSql}")
	private String queryBatchByIdSql;

	/**
	 * select * from exam where userId=? order by createtime desc
	 */
	@Value("${examDao.queryByUserIdSql}")
	private String queryByUserIdSql;

	@Value("${examDao.queryAllExamSql}")
	private String queryAllExamSql;

	@Value("${examDao.updateActivityExamSql}")
	private String updateActivityExamSql;

	/**
	 * select * from cell where examId=?
	 */
	@Value("${examDao.queryAllCellsSql}")
	private String queryAllCellsSql;
	
	/**
	 * update exam set  submitNo=submitNo+1 where id=?
	 */
	@Value("${examDao.updateSubmitNoByOneSql}")
	private String updateSubmitNoByOneSql;

	@Override
	public Exam queryLatestExam() {
		List<Exam> exams = jdbcTemplate.query(queryLatestExamSql,
				ExamMapper.getMapper());
		if (exams == null || exams.size() <= 0) {
			return null;
		} else {
			return exams.get(0);
		}
	}

	@Override
	public List<Exam> queryExamByUpdatetime(Date date) {
		SimpleDateFormat formattime = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String dateStr = formattime.format(date);
		// 数据库时间的比较格式要一致
		String dateFormatStr = "date_format('" + dateStr
				+ "','%Y-%m-%d %H:%i:%s')";

		return jdbcTemplate.query(queryExamByUpdatetimeSql,
				ExamMapper.getMapper(), dateFormatStr);
	}

	@Override
	public List<Exam> queryAllExamForLucene(int currentPage) {
		Page page = new Page();
		page.setCurpage(currentPage);
		page.setPageSize(lucenePageSize);

		return getPaginationResult(queryAllExamForLuceneSql, page,
				ExamMapper.getMapper(), new Object());
	}

	@Override
	public int queryExamNumber() {
		return jdbcTemplate.queryForInt(queryExamNumberSql);
	}

	@Override
	public long insert(long userId, String userName, String title,
			String introduction, int cellNo, boolean active, int repeatFrom,
			int repeatTo, PlayMode playMode, int repeatTime, Timer timer,
			ExamType examType) {

		return this.insertWithIdReturn(insertSql, userId, userName, title,
				introduction, cellNo, active, repeatFrom, repeatTo,
				playMode.toString(), repeatTime, timer.getH(), timer.getM(),
				timer.getS(), examType.toString());
	}

	@Override
	public void update(long examId, String title, String introduction,
			int cellNo, boolean active, int repeatFrom, int repeatTo,
			PlayMode playMode, int repeatTime, Timer timer, ExamType examType) {

		jdbcTemplate.update(updateSql, title, introduction, cellNo, active,
				repeatFrom, repeatTo, playMode.toString(), repeatTime,
				timer.getH(), timer.getM(), timer.getS(), examType.toString(),
				examId);
	}

	@Override
	public void update(long examId, ExamType examType) {
		jdbcTemplate.update(updateExamTypeSql, examType.toString(), examId);
	}

	@Override
	public Exam queryById(long id) {
		List<Exam> exams = jdbcTemplate.query(queryByIdSql,
				ExamMapper.getMapper(), id);
		if (exams != null && exams.size() > 0) {
			return exams.get(0);
		}
		return null;
	}
	
	@Override
	public Exam queryByIdAndUserId(long id, long userId) {
		List<Exam> exams = jdbcTemplate.query(queryByIdAndUserIdSql,
				ExamMapper.getMapper(), id, userId);
		if (exams != null && exams.size() > 0) {
			return exams.get(0);
		}
		return null;
	}

	@Override
	public List<Exam> queryBatchById(List<Long> examIds) {
		if (examIds.size() == 0) {
			return new ArrayList<Exam>();
		}
		String inSet = "" + examIds.get(0);
		for (int i = 1; i < examIds.size(); i++) {
			inSet += ("," + examIds.get(i));
		}

		return jdbcTemplate.query(queryBatchByIdSql, ExamMapper.getMapper(),
				inSet);
	}

	@Override
	public List<Exam> queryByUserId(long userId, Page page, ExamType examType) {

		return this.getPaginationResult(queryByUserIdSql, page,
				ExamMapper.getMapper(), userId, examType.toString());
	}

	@Override
	public List<Exam> queryAll(Page page) {
		return this.getPaginationResult(queryAllExamSql, page,
				ExamMapper.getMapper());
	}

	@Override
	public boolean delete(long id) {
		int i = jdbcTemplate.update(updateActivityExamSql,
				Activity.DELETED.toString(), id);
		if (i > 0) {
			return true;
		}
		return false;
	}

	@Override
	public int queryTotalCount(long userId, ExamType examType) {
		return jdbcTemplate.queryForInt(queryExamNumberSqlByUserId, userId,
				examType.toString());
	}

	@Override
	public List<Cell> queryAllCells(long examId) {
		return jdbcTemplate.query(queryAllCellsSql, CellMapper.getMapper(),
				examId);
	}

	@Override
	public void updateSubmitNoByOne(long examId) {
		jdbcTemplate.update(updateSubmitNoByOneSql, examId);
		//jdbcTemplate.update(updateSubmitNoByOneSql);
	}

}
